import { isReferee } from "@/func";
import { BlockComponentTypes, system } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent } from "@sapi-game/main";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { CvSMaps } from "../map";
import { CvSBackState } from "./backState";

export class CvSMapChooser extends GameComponent<CvSBackState> {
    private readonly signPos = { x: 34, y: -59, z: 61 }; //牌子位置
    private readonly maps = Object.values(CvSMaps);
    private readonly gapTime = 3; //更改地图间隔
    private lastUpdate: number = 0;

    override onAttach(): void {
        this.updateSign();
        this.subscribe(
            Game.events.signClick,
            (e) => {
                if (system.currentTick - this.lastUpdate <= this.gapTime)
                    return;
                if (!isReferee(e.player)) {
                    e.player.sendMessage("你不是裁判，无法切换地图");
                }
                const curMapIndex = this.maps.indexOf(this.state.map);
                const nextMapIndex = (curMapIndex + 1) % this.maps.length;
                this.state.map = this.maps[nextMapIndex]; //更新选择的地图
                this.lastUpdate = system.currentTick;
                system.run(() => {
                    this.updateSign();
                    e.player.playSound("random.click");
                });
            },
            {
                loc: this.signPos,
                dimensionId: DimensionIds.Overworld,
            }
        );
    }

    /**更新牌子 */
    updateSign() {
        try {
            const block = Dimensions.Overworld.getBlock(this.signPos);
            const signComp = block?.getComponent(BlockComponentTypes.Sign);
            if (!signComp) return;
            signComp.setText(
                "§c小鸡§f大战§b牧人\n§a§l游戏开始\n" +
                    `§f地图:${this.state.map.name}`
            );
        } catch (err) {
            console.log(err);
        }
    }
}
